package com.shanpin.shebao.admin.module.channel;

import java.util.List;

import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.shanpin.core.http.MJsonView;
import com.shanpin.shebao.common.URI;
import com.shanpin.shebao.model.Channel;
import com.shanpin.shebao.model.ServiceResult;

@Controller
public class ChannelController {

	@Autowired
	private ChannelService channelService;
	
	@RequestMapping(URI.CHANNEL_MANAGER)
	public Object list() {
		ModelAndView mav = new ModelAndView("setting/channels");
		List<Channel> channelList = channelService.listChannel();
		mav.addObject("channelList", channelList);
		mav.addObject("manager_uri", URI.SBA+URI.CHANNEL_MANAGER);
		mav.addObject("new_uri", URI.SBA+URI.CHANNEL_NEW);
		return mav;
	}
	
	@RequestMapping(URI.CHANNEL_NEW)
	public Object add(String name, String domain, String reg_channel, int pay_channel, String channel_key) {
		if(StringUtil.isBlank(name)) {
			return MJsonView.fail("渠道名为空");
		}
		if(StringUtil.isBlank(reg_channel)) {
			return MJsonView.fail("注册码为空");
		}
		if(StringUtil.isBlank(channel_key)) {
			channel_key = "";
//			return MJsonView.fail("key需要填写");
		}
		if(pay_channel<0) {
			return MJsonView.fail("支付码必须为整数");
		}
		List<Channel> channelList = channelService.listChannel();
		for(Channel channel : channelList) {
			if(channel.getName().equals(name)) {
				return MJsonView.fail("渠道名已存在");
			}
			if(channel.getReg_channel().equals(reg_channel)) {
				return MJsonView.fail("注册码已存在");
			}
			if(channel.getPay_channel() == pay_channel) {
				return MJsonView.fail("支付码已存在");
			}
		}
		ServiceResult<String> sr = channelService.addChannel(name, domain, reg_channel, pay_channel, channel_key);
		if(StringUtil.isNotBlank(sr.msg)) {
			return MJsonView.fail(sr.msg);
		}
		return MJsonView.ok(sr.result);
	}
}
